package com.wulian.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wulian.common.constants.CommonConstants;

/**
 * 
* @ClassName: WebUtil 
* @Description: TODO(获取用户信息) 
* @author 马志豪
* @date 2019年9月11日 下午5:31:36 
*
 */
public class WebUtil {
    private static Logger logger = LoggerFactory.getLogger(WebUtil.class);

    /**
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    public static String getUserInfo(HttpServletRequest request){
        String userInfo = getFromRequest(request, CommonConstants.USER_INFO);
        if (!StringUtils.isBlank(userInfo)) {
            try {
                userInfo = URLDecoder.decode(userInfo,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                logger.error("解析UserInfo报错 {}",e.getMessage());
            }
        }
        return userInfo;
    }

    /**
     * 从请求中返回给定格式的参数
     * @param request
     * @param paramName
     * @param type
     * @return
     */
    public static String getDecodedParameter(HttpServletRequest request, String paramName, String type){

        String parameter =getFromRequest(request,paramName);
        if (!StringUtils.isBlank(parameter)) {
            try {
                parameter = URLDecoder.decode(parameter,type);
            } catch (UnsupportedEncodingException e) {
                logger.error("解析UserInfo报错 {}",e.getMessage());
            }
        }
        return parameter;
    }
    private static String getFromRequest(HttpServletRequest request, String paramName) {
        String value = request.getParameter(paramName);
        if (StringUtils.isBlank(value)) {
            value = request.getHeader(paramName);
            if (StringUtils.isBlank(value)) {
                if (request.getCookies() != null) {
                    for (Cookie cookie : request.getCookies()) {
                        if (cookie.getName().equals(paramName)) {
                            value = cookie.getValue();
                        }
                    }
                }
            }
        }
        return value;
    }
}
